package com.fintecher.controller;

import com.alibaba.fastjson.JSON;
import com.fintecher.pojo.Power;
import com.fintecher.pojo.Role;
import com.fintecher.pojo.User;
import com.fintecher.pojo.UserRole;
import com.fintecher.service.IRolePowerService;
import com.fintecher.service.IRoleService;
import com.fintecher.service.IUserRoleService;
import com.fintecher.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by Administrator on 2017/2/8.
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    private Logger logger = Logger.getLogger(String.valueOf(this.getClass()));
    @Autowired
    private IRolePowerService rolePowerService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRoleService userRoleService;
 /*   @RequestMapping(value = "toUGM",method = RequestMethod.GET)
    private String toUGM(){

        return "user_group_manage";
    }
*/




    /**
     * 添加角色
     * @param
     * @return
     */
    @RequestMapping(value = "addRoles",method = RequestMethod.POST)
    public void addRole(@RequestParam(value = "id[]") String [] id, String roleName, String remark, HttpServletRequest request,
                        HttpServletResponse response, HttpSession session)throws Exception {

        //从session中获取用户id
        User user = (User)session.getAttribute( "user" );
        //将数组转换为list
        if(roleName != null){

            //添加角色返回主键id，role.getId()可以调出角色id
            Role role = new Role();
            role.setRoleName(roleName);
            role.setRemark(remark);
            role.setCreatePerson(user.getId());
            roleService.addRole(role);

            // * 用户角色添加，为登录用户添加角色权限
            UserRole userRole = new UserRole();
            userRole.setRoleid(role.getId());
            userRole.setUserid(user.getId());
            userRoleService.addUserRole(userRole);

            //为角色添加权限
            if(null != id){
                for(int i=0;i<id.length;i++){
                    Role role1 = new Role();
                    role1.setRoleId(role.getId());
                    role1.setPowerId(Integer.parseInt(id[i]));
                    rolePowerService.addPowerRole(role1);
                }
            }
        }

        String result = "success";
        response.getWriter().write(result);
    }

    /**
     * 查询所有用户组下面的用户
     * @param role
     * @return
     */

   /* @RequestMapping(value = "selRoleGroupUser")
    public String selRoleGroupUser(@RequestBody Role role){
        List<User> roleList =  roleService.selRoleGroupUser(role);
        logger.info(JSON.toJSONString(roleList));
        return "";
    }
*/

    /**
     * 删除角色
     * @param
     * @return
     */

    @RequestMapping(value ="delRole",method = RequestMethod.POST)
    public void delRole(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        roleService.delRole(Integer.parseInt(id));
        String mes = "abc";
        response.getWriter().write(mes);
//        response.sendRedirect("http://localhost:8080/power/selPower");
    }

    /**
     * 2.27  10.25进行修改
     * @param role
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "selAllPower")
    public String  selAllPower(Role role,HttpServletRequest request,HttpSession session){
        User user = (User) session.getAttribute("user");
        role.setUserId(user.getId());

        List<Role> roleList = roleService.selAllPower(role);
        logger.info(JSON.toJSONString(roleList));
        request.setAttribute("roles",roleList);
        return "user_group_manage";
    }

    /**
     * 用户审核功能，查看用户是否有审核功能
     * @param user
     * @return
     */
    @RequestMapping(value = "describesRole")
    public String describesRole( User user,Integer state,HttpSession session,
                                 HttpServletResponse response) throws Exception{
        User userSession = (User) session.getAttribute("user");
        //审核人为当前登录用户id
        user.setDescribesPerson(userSession.getId());
        //查看用户是否有审核功能
        List<Role> roleList = roleService.describesRole(userSession);
        //判断经办和审核是不是一个人
        Integer userSessionID=userSession.getId();
        Integer userId = user.getId();
        if(userSessionID==userId){
            String abc="success";
            response.getWriter().write(abc);
        }else {
            if (state == 2) {
                for (int i = 0; i < roleList.size(); i++) {
                    if (roleList.get(i).getPowerId() == 77) {
                        user.setState(2);
                        userService.updateUserState(user);
                        break;
                    }
                }
                String abc="success";
                response.getWriter().write(abc);
            }else if (state == 3) {
                for (int i = 0; i < roleList.size(); i++) {
                    if (roleList.get(i).getPowerId() == 77) {
                        user.setState(3);
                        userService.updateUserState(user);
                        break;
                    }
                }
                String abc="success";
                response.getWriter().write(abc);
            }
        }
        return "user_manage";

    }
    /**
     * 用户组审核功能
     * @param user
     * @return
     */
    @RequestMapping(value = "describesRoleGroup")
    public void describesRoleGroup(Role role,Integer id,Integer userId, User user,Integer state,HttpSession session,
                                     HttpServletResponse response) throws  Exception{
        User userSession = (User) session.getAttribute("user");
        //审核人为当前登录用户id
        user.setId(userSession.getId());
        role.setDescribesPerson(userSession.getId());
        //查看用户是否有审核功能
        List<Role> roleGroupList = roleService.describesRole(user);
       /* if(userSession.getId() ==userId){
            String abc="success";
            response.getWriter().write(abc);
        }else {}*/

        if (state == 1) {
            for (int i = 0; i < roleGroupList.size(); i++) {
                if (roleGroupList.get(i).getPowerId() == 77) {
                    role.setId(id);
                    role.setState(1);
                    //修改用户组状态
                    roleService.updateRoleGroup(role);
                    //修改用户组审核人
                    roleService.updateRoleGroupDes(role);
                    break;
                }
            }
            String abc="success";
            response.getWriter().write(abc);
        }else if(state ==2){
            for (int i = 0; i < roleGroupList.size(); i++) {
                if (roleGroupList.get(i).getPowerId() == 77) {
                    role.setId(id);
                    role.setState(2);
                    //修改用户组状态
                    roleService.updateRoleGroup(role);
                    //修改用户组审核人
                    roleService.updateRoleGroupDes(role);
                    break;
                }
            }
            String abc="success";
            response.getWriter().write(abc);
        }

    }


}
